package com.gistone.commis.api.restController;

import com.gistone.commis.constant.Status;
import com.gistone.commis.database.GetBySqlMapper;
import com.gistone.commis.dto.EditorResult;
import com.gistone.commis.dto.FieldError;
import com.gistone.commis.dto.Option;
import com.gistone.commis.dto.Options;
import com.gistone.commis.entity.Community;
import com.gistone.commis.entity.Depart;
import com.gistone.commis.entity.User;
import com.gistone.commis.entity.UserType;
import com.gistone.commis.mapper.CommunityMapper;
import com.gistone.commis.mapper.DepartMapper;
import com.gistone.commis.mapper.UserMapper;
import com.gistone.commis.mapper.UserTypeMapper;
import com.gistone.commis.service.UserService;
import com.gistone.commis.util.DataTablePageUtil;
import com.gistone.commis.dto.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangfan on 2017/5/1.
 */
@RestController("apiUserController")
@RequestMapping("api/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private GetBySqlMapper getBySqlMapper;


    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;

    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private DepartMapper departMapper;
    @Autowired
    private UserService userService;

    /**
     *
     * @param id
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/password")
    public Result password(@RequestParam int id,@RequestParam String opassword,@RequestParam String password,@RequestParam String rpassword) {

        User user =userMapper.selectByPrimaryKey(id);

        if(!passwordEncoder.matches(opassword,user.getUserPwd())){
            return new Result(Status.ERROR,"旧密码输入错误，请重新输入！","");
        }
        System.out.println("1--"+password);
        System.out.println("2--"+rpassword);
        if(!password.equals(rpassword)){
            return new Result(Status.ERROR,"两次输入密码不一致，请重新输入！","");
        }

        user.setUserPwd(passwordEncoder.encode(password));

        userMapper.updateByPrimaryKey(user);
        Authentication authentication =new UsernamePasswordAuthenticationToken(user,user.getUserPwd(),user.getRoles());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return new Result(Status.ERROR,"密码更新成功！");
    }
    /**
     * 获取所有用户
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/all")
    public List<User> loadAll() {
        System.out.println(this.userMapper.findUsers().size());
        return this.userMapper.findUsers();
    }

    /**
     * 新建y用户信息
     *
     * @param request
     * @param response
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "/create")
    public Object create(HttpServletRequest request, HttpServletResponse response) {


        User user = new User();
        EditorResult<User> userEditorResult = new EditorResult<>();
        List<FieldError> fieldErrorList = new ArrayList<>();
//        house.setHouseId(houseId);
        user = getUser (request, "data[0][", user);
        user.setUserPwd(passwordEncoder.encode("123456"));


/*
        if(fieldErrorList.size()>0){
            userEditorResult.setFieldErrors(fieldErrorList);
//            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return userEditorResult;
        }*/
        if (userMapper.insertSelective(user)> 0) {
            try {
                userMapper.insertUserRole(user.getUserId(),1);
            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
            List<User> data = new ArrayList<>();
            data.add(userMapper.selectByPrimaryKey(user.getUserId()))	;
            userEditorResult.setData(data);
        } else {
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }


        return userEditorResult;
//        String jsonString = JSON.toJSONString(userEditorResult);
//
//        return jsonString;
    }

    /**
     * 批量修改用户信息， id以,号分割
     *
     * @param houseIdStr
     * @param request
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.PUT, value = "/edit")
    public Object edit(@RequestParam("id") String houseIdStr, HttpServletRequest request, HttpServletResponse response) {
        String[] arr = houseIdStr.split(",");
        EditorResult<User> userEditorResult = new EditorResult<>();

        List<User> data =new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            int userId = Integer.valueOf(arr[i]);

            System.out.println(userId);
            User user = new User();

            user.setUserId(userId);
            user= getUser(request, "data[" + userId + "][", user);

            if (userMapper.updateByPrimaryKeySelective(user) > 0) {
                data.add(userMapper.selectByPrimaryKey(userId));


            }else{
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }


        }

        userEditorResult.setData(data);
        return userEditorResult;


    }


    /**
     * 用户删除
     * 通过用户ID批量删除用户信息， id以,号分割
     *
     * @param userIdStr
     * @param request
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.DELETE, value = "/remove")
    public Object remove(@RequestParam("id") String userIdStr, HttpServletRequest request, HttpServletResponse response) {
        String[] arr = userIdStr.split(",");
        EditorResult<User> userEditorResult = new EditorResult<>();
        for (int i = 0; i < arr.length; i++) {
            int userId = Integer.valueOf(arr[i]);
            if (userMapper.deleteByPrimaryKey(userId) > 0) {
                System.out.println("删除" + userId + "成功！");


            } else {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
        }
        return userEditorResult;


    }

    /**
     * dataTables 表单数据返回
     *
     * @param request
     * @return
     */

    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = "/pageDatatables")
    public DataTablePageUtil<User> pageDatatables(HttpServletRequest request, User user) {
//		HttpSession httpSession = request.getSession();
//		User user = (User) httpSession.getAttribute("userInfo");
//		logger.info("用户信息：" + user.toString());
//		int community_id = user.getCommunity().getCommunityId();
//		user.setCommunityId(community_id);
        System.out.println(user.toString());

        List<Community> communities =communityMapper.findCommunitys();
        Options os =new Options();
        List<Option> optionList =new ArrayList<>();
        for (Community community : communities) {

            Option option =new Option();
            option.setLabel(community.getCommunityName());
            option.setValue(community.getCommunityId());
            optionList.add(option);


        }
        os.setCommunityId(optionList);
        List<Depart> departs =departMapper.findDeparts();
        optionList =new ArrayList<>();
        for (Depart depart : departs) {

            Option option =new Option();
            option.setLabel(depart.getDepartName());
            option.setValue(depart.getDepartId());
            optionList.add(option);


        }

        os.setDepartId(optionList);

        List<UserType> userTypes =userTypeMapper.findUserTypes();
        optionList =new ArrayList<>();
        for (UserType userType : userTypes) {

            Option option =new Option();
            option.setLabel(userType.getUserTypeName());
            option.setValue(userType.getUserTypeId());
            optionList.add(option);


        }

        os.setUserTypeId(optionList);


        List<User> parentUsers =userMapper.findUserLeads();
        optionList =new ArrayList<>();
        for (User parentUser : parentUsers) {

            Option option =new Option();
            option.setLabel(parentUser.getRealName());
            option.setValue(parentUser.getUserId());
            optionList.add(option);


        }

        os.setParentId(optionList);

        DataTablePageUtil<User> dataTable = new DataTablePageUtil<>(request);

        PageHelper.startPage(dataTable.getPage_num(), dataTable.getPage_size());
        List<User> list = userMapper.selectSelective(user);
        PageInfo<User> pageInfo =new PageInfo<>(list);
        dataTable.setDraw(dataTable.getDraw());
        dataTable.setData(pageInfo.getList());
        dataTable.setOptions(os);
        dataTable.setRecordsTotal((int)pageInfo.getTotal());
        dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
        //返回数据到页面


        return dataTable;

    }

    private User getUser(HttpServletRequest request, String prefix, User user) {



        user.setUserName(request.getParameter(prefix + "userName]"));
        user.setRealName(request.getParameter(prefix + "realName]"));
        user.setUserPhone(request.getParameter(prefix + "userPhone]"));
        user.setUserEmail(request.getParameter(prefix + "userEmail]"));
        user.setImage(request.getParameter(prefix + "image]"));
        user.setCommunityId(Integer.valueOf(request.getParameter(prefix + "communityId]")));
        user.setDepartId(Integer.valueOf(request.getParameter(prefix + "departId]")));
        user.setParentId(Integer.valueOf(request.getParameter(prefix + "parentId]")));
        user.setUserTypeId(Integer.valueOf(request.getParameter(prefix + "userTypeId]")));


        System.out.println(user.toString());
        return user;


    }



 

    /**
     * 获取当前用户信息
     * @return
     */
    @RequestMapping("/currentUser")
	@PreAuthorize("hasAnyAuthority('ROLE_USER','ROLE_ADMIN','ROLE_DBA')")
    public Result currentUserName() {
        String username =SecurityContextHolder
                .getContext()
                .getAuthentication()
                .getName();
        System.out.println(username);
        Result result =new Result();
        User user =new User();
        user.setUserName(username);
       List<User> users = userMapper.selectSelective(user);
        if(users.size()==1){
            result.setStatus(0);
            result.setData(users.get(0));
            result.setMsg("成功");

        }else{
            result.setStatus(1);
            result.setMsg("没有登录");
        }
        return result;
    }


    /**
     * 通过用户ID获取用户
     *
     * @param id
     * @return
     */

    @RequestMapping(value = "/{id}")
//	@PreAuthorize("hasRole('ROLE_USER')")
    public User user(@PathVariable int id) {
        User user = userMapper.findUserById(1);
        return user;
    }



    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    @PreAuthorize("hasRole('USER')")
    public User getUserInfo(User user1) {
        User user = new User();

        return user;
    }


    @RequestMapping(value = "/getAuth", method = RequestMethod.GET)
    @PreAuthorize("hasRole('ADMIN')")
    public User getAuth(User user) {
        User userInfo = new User();
        return userInfo;
    }


}


